package com.iqiyi.dbagent.base.config;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iqiyi.dbagent.base.config.i.Configuration;
import com.iqiyi.dbagent.base.utils.text.StringUtil;
import com.iqiyi.dbagent.base.utils.time.DateUtil;
import com.iqiyi.dbagent.model.Table4QiData;

public class MySqlConfig extends Configuration {

	private static final  String configName = "config.properties";

	private volatile static MySqlConfig instance = null;

	private static final Logger logger = LoggerFactory.getLogger(MySqlConfig.class);
	
	public MySqlConfig() {
		super(configName);
		initSelfConfig();
	}

	public MySqlConfig(String configName) {
        super(configName);
        initSelfConfig();
    }

	public static MySqlConfig getInstance() {
		if (instance == null) {
			synchronized (MySqlConfig.class) {
				if (instance == null) {
					instance = new MySqlConfig();
				}
			}
		}
		return instance;
	}
	
	/**
	 * 初始化
	 */
	public void initSelfConfig(){
	    String execSize = getValue("threadPoll.size");
	    if(null!=execSize && !"".equals(execSize)){
	        if(execSize.toLowerCase().indexOf("auto-") != -1){
                int nsize = Integer.parseInt(execSize.split("-")[1] != null ? execSize.split("-")[1] : "4");
	            setExcuteBatchSize(Runtime.getRuntime().availableProcessors()*nsize);
	        }else{
	            setExcuteBatchSize(Integer.parseInt(execSize));
	        }
	    }
	    setSqlBufferSize(Integer.parseInt(getValue("sqlBuffer.size")));
	    setExcuteBatchSize(Integer.parseInt(getValue("excuteBatch.size")));
	    Map<String,Table4QiData> tabMap = new ConcurrentHashMap<String, Table4QiData>();
	    String[] tabTags = getValue("business").split(",");
	    String typeFilter = getValue("log_type_filter");
	    this.setBusiTypeFilter(typeFilter);
	    Map<String,String> reMap = new ConcurrentHashMap<String, String>();
	    for(String tbTag:tabTags){
	        Table4QiData qdata = new Table4QiData();
	        Map<String, Double> valuesMap = new ConcurrentHashMap<String, Double>();
	        String keyl = tbTag+".tab_name";
	        String tabName = getValue(keyl);
	        qdata.setSrcTableName(tabName);
	        Date dataTime = new Date();
	        if(null != getDataTime()){
	            dataTime = getDataTime();
	        }
	        if(tabName.indexOf(CommParme.timeStartReg)!=-1 && tabName.indexOf(CommParme.timeEndReg)!=-1){
                String regStr = StringUtil.getMiddStr(tabName, CommParme.timeStartReg, CommParme.timeEndReg);
                tabName = tabName.replace(CommParme.timeStartReg+regStr+CommParme.timeEndReg, DateUtil.formatDateByFormat(dataTime, regStr,Locale.CHINA));
	        }
	        reMap.put(keyl, tabName);
	        qdata.setTableName(tabName);
	        qdata.setTableTag(getValue(tbTag+".log_tag"));
	        qdata.setLogKeyFilter(getValue(tbTag+".log_key_filter"));
	        qdata.setLogValueFilter(getValue(tbTag+".log_value_filter"));
	        qdata.setTagFilter(typeFilter);
	        qdata.setTabId(getValue(tbTag+".tab_id"));
	        if(null!=getValue(tbTag+".log_fileds") && !"".equals(getValue(tbTag+".log_fileds"))){
	            String[] fileds = getValue(tbTag+".log_fileds").split(",");
	            List<String> filedsList = new ArrayList<String>();
	            for(String filed:fileds){
	                filedsList.add(filed);
	            }
	            qdata.setFiledsList(filedsList);
	        }
	        if(null!=getValue(tbTag+".log_fileds") && !"".equals(getValue(tbTag+".log_fileds"))){
                String[] fileds = getValue(tbTag+".log_fileds").split(",");
                List<String> filedsList = new ArrayList<String>();
                for(String filed:fileds){
                    filedsList.add(filed);
                }
                qdata.setFiledsList(filedsList);
            }
	        if(null!=getValue(tbTag+".value_fileds") && !"".equals(getValue(tbTag+".value_fileds"))){
                String[] vfileds = getValue(tbTag+".value_fileds").split(",");
                for(String filed:vfileds){
                    valuesMap.put(filed, 0d);
                }
            }
            qdata.setValuesMap(valuesMap );
	        if(null!=getValue(tbTag+".init_sql") && !"".equals(getValue(tbTag+".init_sql"))){
	            String[] sqlstr = getValue(tbTag+".init_sql").split(";");
	            List<String> sqls = new ArrayList<String>();
	            Set<String> keySet = reMap.keySet();
	            for(String sql:sqlstr){
	                if(sql!=null && !"".equals(sql.trim())){
	                    for(String key:keySet){
	                        sql = sql.replace(CommParme.timeStartReg+key+CommParme.timeEndReg, reMap.get(key));
	                    }
	                    //logger.info("sql:{}",sql);
	                    sqls.add(sql);
	                }
	            }
	            qdata.setSqls(sqls);
	        }
	        //logger.info(qdata.toString());
	        tabMap.put(tbTag, qdata);
	    }
	    logger.info("加载配置信息完成...");
	    setTableMap(tabMap);
	}
}
